<template>
  <div class="compound-input-wrapper">
    <!-- 普通编辑模式：使用SmartTextInput -->
    <div v-if="!isEditMode" class="smart-input-container">
      <SmartTextInput
        v-model="inputValue"
        v-bind="textInputProps"
        @update:modelValue="handleInputChange"
        @select="handleSuggestionSelect" />
    </div>

    <!-- 复合编辑模式：contenteditable + 内联输入框 -->
    <div v-else class="inline-edit-container">
      <!-- 智能搜索输入框（用于搜索建议） -->
      <div class="smart-search-wrapper" v-if="showSmartSearch">
        <SmartTextInput
          v-model="searchValue"
          v-bind="textInputProps"
          placeholder="输入关键词搜索模板..."
          @update:modelValue="handleSearchInput"
          @select="handleTemplateSelect"
          style="margin-bottom: 8px" />
      </div>

      <!-- 使用contenteditable的div作为大输入框 -->
      <div
        ref="editableRef"
        class="editable-text-area"
        contenteditable="true"
        @blur="handleTextChange"
        @focus="
          () => {
            isFocused = true
            console.log('contenteditable获得焦点')
          }
        "
        @keydown="handleKeyDown"
        @keyup="handleKeyUp">
        <!-- 文本内容和小输入框混合显示 -->
        <span class="text-content">
          <span>{{ preText }}</span>
          <span v-html="content1"></span>
        </span>
        <input v-model="yearValue" type="number" placeholder="年" class="protected-input" @input="handleYearInput" />
        <span class="text-content">年</span>
        <input v-model="monthValue" type="number" placeholder="月" class="protected-input" @input="handleMonthInput" />
        <span class="text-content">月</span>
        <input v-model="dayValue" type="number" placeholder="日" class="protected-input" @input="handleDayInput" />
        <span class="text-content">日</span>
        <span v-html="content2" class="text-content"></span>
      </div>

      <!-- 智能建议面板 -->
      <div v-if="showSuggestions && bestMatch" class="suggestions-panel">
        <div class="suggestions-header">模板建议 (按Tab键补全)</div>
        <div
          v-for="item in bestMatch"
          :key="item.id"
          :class="['suggestion-item', 'active']"
          @click="applySuggestion(item)">
          <div class="suggestion-content" v-html="item.highlightedContent"></div>
          <div class="suggestion-similarity">匹配度: {{ Math.round(item.similarity * 100) }}%</div>
        </div>
      </div>

      <!-- 隐藏的textarea用于表单验证和数据绑定 -->
      <textarea :value="modelValue" style="display: none" ref="hiddenTextarea"></textarea>
    </div>
  </div>
</template>

<script setup name="CompoundInput">
import { ref, computed, watch, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import SmartTextInput from '@/components/SmartTextInput/index.vue'
import useCompleteContent from '@/hooks/completeContent.js'
import { commontermsGet } from '@/api/filingReview/register.js'

// 定义props
const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  // 编辑模式，是否显示年月日输入框
  isEditMode: {
    type: Boolean,
    default: true,
  },
  // 前置文本（在日期之前的文本）
  preText: {
    type: String,
    default: '',
  },
  // 年月日的初始值
  yearField: {
    type: [Number, String, undefined],
    default: undefined,
  },
  monthField: {
    type: [Number, String, undefined],
    default: undefined,
  },
  dayField: {
    type: [Number, String, undefined],
    default: undefined,
  },
  // 日期前后的内容
  content1: {
    type: String,
    default: '',
  },
  content2: {
    type: String,
    default: '',
  },
  // 智能搜索相关配置
  contentType: {
    type: String,
    default: '200', // 案情说明模板类型
  },
  minLength: {
    type: Number,
    default: 2,
  },
  maxSuggestions: {
    type: Number,
    default: 5,
  },
  // 传递给SmartTextInput的其他属性
  placeholder: {
    type: String,
    default: '请输入内容',
  },
  type: {
    type: String,
    default: 'textarea',
  },
  rows: {
    type: Number,
    default: 4,
  },
})

// 定义emits
const emit = defineEmits([
  'update:modelValue',
  'update:year',
  'update:month',
  'update:day',
  'update:content1',
  'update:content2',
])

// 引用和数据
const editableRef = ref(null)
const hiddenTextarea = ref(null)
const { setCompleteContent } = useCompleteContent()

// 智能搜索相关状态
const showSmartSearch = ref(false)
const searchValue = ref('')
const showSuggestions = ref(false)
const suggestions = ref([])
const isFocused = ref(false)
const currentKeyword = ref('')

// 内部状态管理年月日值
const yearValue = ref(props.yearField || '')
const monthValue = ref(props.monthField || '')
const dayValue = ref(props.dayField || '')

// 双向绑定输入值
const inputValue = computed({
  get: () => props.modelValue,
  set: value => emit('update:modelValue', value),
})

// 传递给SmartTextInput的属性
const textInputProps = computed(() => ({
  placeholder: props.placeholder,
  type: props.type,
  rows: props.rows,
  minLength: props.minLength,
  maxSuggestions: props.maxSuggestions,
  contentType: props.contentType,
}))

// 最佳匹配项
const bestMatch = computed(() => {
  if (suggestions.value.length === 0) return null
  return suggestions.value.slice(0, props.maxSuggestions)
})

// 监听props变化更新内部状态
watch(
  () => props.yearField,
  newVal => {
    yearValue.value = newVal || ''
  }
)
watch(
  () => props.monthField,
  newVal => {
    monthValue.value = newVal || ''
  }
)
watch(
  () => props.dayField,
  newVal => {
    dayValue.value = newVal || ''
  }
)

// 监听内部状态变化发射事件
watch(yearValue, newVal => {
  emit('update:year', newVal)
})
watch(monthValue, newVal => {
  emit('update:month', newVal)
})
watch(dayValue, newVal => {
  emit('update:day', newVal)
})

// 输入处理函数
const handleYearInput = event => {
  yearValue.value = event.target.value
}

const handleMonthInput = event => {
  monthValue.value = event.target.value
}

const handleDayInput = event => {
  dayValue.value = event.target.value
}

// 普通模式的输入处理
const handleInputChange = value => {
  emit('update:modelValue', value)
}

// 智能建议选择处理
const handleSuggestionSelect = item => {
  emit('update:modelValue', item.content)
}

// 模板搜索处理
const handleSearchInput = value => {
  searchValue.value = value
}

// 模板选择处理
const handleTemplateSelect = item => {
  // 将选中的模板应用到contenteditable区域
  if (editableRef.value) {
    const template = item.content
    // 解析模板中的日期信息
    const parsed = parseDateNumbers(template)
    if (parsed) {
      emit('update:modelValue', template)
      nextTick(() => {
        updateEditableContent()
      })
    }
  }
  searchValue.value = ''
  showSmartSearch.value = false
}

// 获取模板库
const getTemplateDatabase = async () => {
  try {
    console.log('获取模板库，contentType:', props.contentType)
    const res = await commontermsGet({
      termType: props.contentType, // 使用传入的contentType
      pageSize: 9999,
      pageNum: 1,
      status: 0,
    })
    console.log('模板库数据:', res.data)

    // 如果API没有返回数据，使用测试数据
    if (!res.data || res.data.length === 0) {
      console.log('API无数据，使用测试模板')
      return [
        {
          id: 1,
          content: '我局于2021年01月01日对你单位上述行为进行立案调查，经查实确认你单位存在违法行为。',
        },
        {
          id: 2,
          content: '我局于2022年06月15日对该违法行为进行现场检查，发现存在环境污染问题。',
        },
        {
          id: 3,
          content: '经我局调查核实，该单位在2023年03月20日确实存在违反相关法律法规的行为。',
        },
      ]
    }

    return res.data || []
  } catch (error) {
    console.error('获取模板库失败:', error)
    // 返回测试数据作为fallback
    return [
      {
        id: 1,
        content: '我局于2021年01月01日对你单位上述行为进行立案调查，经查实确认你单位存在违法行为。',
      },
      {
        id: 2,
        content: '我局于2022年06月15日对该违法行为进行现场检查，发现存在环境污染问题。',
      },
      {
        id: 3,
        content: '经我局调查核实，该单位在2023年03月20日确实存在违反相关法律法规的行为。',
      },
    ]
  }
}

// 计算文本相似度
const calculateSimilarity = (str1, str2) => {
  if (!str1 || !str2) return 0

  const text1 = str1.toLowerCase()
  const text2 = str2.toLowerCase()

  // 完全包含匹配
  if (text2.includes(text1)) return 0.9
  if (text1.includes(text2)) return 0.8

  // 关键词匹配
  const keywords1 = text1.split(/[\s，。！？；：、]+/).filter(k => k.length > 0)
  const keywords2 = text2.split(/[\s，。！？；：、]+/).filter(k => k.length > 0)

  let matches = 0
  for (const keyword of keywords1) {
    if (keyword.length < 2) continue
    if (keywords2.some(k => k.includes(keyword) || keyword.includes(k))) {
      matches++
    }
  }

  return matches / Math.max(keywords1.length, keywords2.length)
}

// 高亮匹配的关键词
const highlightKeywords = (text, keywords) => {
  if (!keywords.length) return text

  let result = text
  keywords.forEach(keyword => {
    if (keyword.length >= 2) {
      const regex = new RegExp(`(${keyword})`, 'gi')
      result = result.replace(regex, '<mark class="highlight">$1</mark>')
    }
  })

  return result
}

// 智能搜索处理
const handleSmartSearch = async inputText => {
  console.log('智能搜索开始，输入文本:', inputText)
  if (!inputText || inputText.length < props.minLength) {
    showSuggestions.value = false
    return
  }

  // 获取最后输入的关键词
  const words = inputText
    .trim()
    .split(/[\s，。！？；：、]+/)
    .filter(w => w.length > 0)
  const lastWord = words[words.length - 1]
  console.log('提取关键词:', lastWord)

  if (lastWord.length < props.minLength) {
    showSuggestions.value = false
    return
  }

  currentKeyword.value = lastWord

  // 搜索匹配的模板
  const database = await getTemplateDatabase()
  console.log('模板库长度:', database.length)
  const matches = database
    .map(item => ({
      ...item,
      similarity: calculateSimilarity(lastWord, item.content),
      highlightedContent: highlightKeywords(item.content, [lastWord]),
    }))
    .filter(item => item.similarity > 0.1)
    .sort((a, b) => b.similarity - a.similarity)

  console.log('匹配结果:', matches.length)
  console.log('焦点状态:', isFocused.value)
  suggestions.value = matches
  showSuggestions.value = matches.length > 0 && isFocused.value
  console.log('显示建议面板:', showSuggestions.value)
}

// 应用建议
const applySuggestion = item => {
  console.log('applySuggestion 被调用，item:', item)
  if (!editableRef.value) {
    console.log('editableRef.value 为空')
    return
  }

  // 替换整个内容
  const template = item.content
  console.log('应用建议模板:', template)

  // 直接更新contenteditable的内容
  editableRef.value.innerHTML = template

  emit('update:modelValue', template)

  // 解析模板中的日期信息
  const parsed = parseDateNumbers(template)
  console.log('解析的日期信息:', parsed)

  showSuggestions.value = false

  // 更新编辑器内容
  nextTick(() => {
    handleTextChange() // 触发文本变化处理
    editableRef.value?.focus()
  })
}

// 从文本中解析年月日数字
const parseDateNumbers = text => {
  const datePattern = /(\d{4})年?(\d{1,2})月?(\d{1,2})日?/
  const match = text.match(datePattern)

  if (match) {
    const matchStart = match.index || 0
    const matchEnd = matchStart + match[0].length

    const beforeMatch = text.substring(0, matchStart)
    const afterMatch = text.substring(matchEnd)

    yearValue.value = match[1] || ''
    monthValue.value = match[2] || ''
    dayValue.value = match[3] || ''

    emit('update:year', yearValue.value)
    emit('update:month', monthValue.value)
    emit('update:day', dayValue.value)
    emit('update:content1', beforeMatch)
    emit('update:content2', afterMatch)

    return {
      year: match[1],
      month: match[2],
      day: match[3],
      before: beforeMatch,
      after: afterMatch,
    }
  }
  return null
}

// 处理文本变化
const handleTextChange = () => {
  if (!editableRef.value) return

  const fullText = editableRef.value.innerText || editableRef.value.textContent || ''

  if (props.isEditMode) {
    const parsed = parseDateNumbers(fullText)
    if (parsed) {
      emit('update:content1', parsed.before)
      emit('update:content2', parsed.after)
    }
  }

  emit('update:modelValue', fullText)
}

// 处理键盘事件
const handleKeyDown = event => {
  // 智能搜索快捷键
  if ((event.ctrlKey || event.metaKey) && event.key === 'k') {
    event.preventDefault()
    showSmartSearch.value = !showSmartSearch.value
    if (showSmartSearch.value) {
      nextTick(() => {
        // 聚焦搜索框
      })
    }
    return
  }

  // Tab键补全
  if (event.key === 'Tab') {
    console.log('Tab键按下，showSuggestions:', showSuggestions.value, 'bestMatch:', bestMatch.value)
    if (showSuggestions.value && bestMatch.value && bestMatch.value.length > 0) {
      event.preventDefault()
      console.log('应用第一个建议:', bestMatch.value[0])
      applySuggestion(bestMatch.value[0])
      return
    }
  }

  // Escape键关闭建议
  if (event.key === 'Escape') {
    showSuggestions.value = false
    showSmartSearch.value = false
    return
  }

  // 可以在这里添加一些特殊键的处理
  if (event.key === 'Enter') {
    event.preventDefault()
    handleTextChange()
  }
}

// 处理键盘抬起事件（用于触发智能搜索）
const handleKeyUp = async event => {
  if (!editableRef.value) return

  // 忽略特殊键
  if (['Tab', 'Escape', 'Enter', 'Shift', 'Control', 'Alt', 'Meta'].includes(event.key)) {
    return
  }

  const fullText = editableRef.value.innerText || editableRef.value.textContent || ''

  // 触发智能搜索
  await handleSmartSearch(fullText)
}

// 更新编辑器内容
const updateEditableContent = () => {
  nextTick(() => {
    if (editableRef.value && !props.isEditMode) {
      editableRef.value.innerHTML = props.modelValue || ''
    }
  })
}

// 监听modelValue变化
watch(() => props.modelValue, updateEditableContent)

// 组件挂载时初始化
onMounted(() => {
  updateEditableContent()

  // 如果有初始的年月日值，设置内部状态
  if (props.yearField) yearValue.value = props.yearField
  if (props.monthField) monthValue.value = props.monthField
  if (props.dayField) dayValue.value = props.dayField

  // 自动补全功能
  nextTick(() => {
    if (hiddenTextarea.value) {
      setCompleteContent(hiddenTextarea.value)
    }
  })

  // 设置焦点事件
  nextTick(() => {
    if (editableRef.value) {
      console.log('设置焦点事件监听器')
      editableRef.value.addEventListener('focus', () => {
        console.log('获得焦点')
        isFocused.value = true
      })
      editableRef.value.addEventListener('blur', () => {
        console.log('失去焦点')
        isFocused.value = false
        setTimeout(() => {
          if (!isFocused.value) {
            showSuggestions.value = false
          }
        }, 200)
      })
    } else {
      console.log('editableRef.value 为空，无法设置焦点事件')
    }
  })
})
</script>

<style lang="scss" scoped>
.compound-input-wrapper {
  position: relative;
  width: 100%;
}

.smart-input-container {
  position: relative;
  width: 100%;
}

.smart-search-wrapper {
  margin-bottom: 8px;
}

.inline-edit-container {
  position: relative;
  width: 100%;
}

.editable-text-area {
  min-height: 100px;
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 12px;
  font-size: 14px;
  line-height: 1.5;
  color: #606266;
  background-color: #fff;
  outline: none;
  resize: none;
  box-sizing: border-box;

  &:focus {
    border-color: #409eff;
    outline: none;
  }

  .text-content {
    display: inline;
    vertical-align: middle;
  }

  .protected-input {
    display: inline-block;
    width: 60px;
    height: 24px;
    line-height: 24px;
    padding: 0 8px;
    border: 1px solid #409eff;
    border-radius: 3px;
    font-size: 12px;
    text-align: center;
    margin: 0 2px;
    vertical-align: middle;
    background-color: #f0f9ff;

    &:focus {
      outline: none;
      border-color: #66b1ff;
      background-color: #fff;
    }

    /* 隐藏number input的上下箭头 */
    &::-webkit-outer-spin-button,
    &::-webkit-inner-spin-button {
      -webkit-appearance: none;
      margin: 0;
    }

    /* Firefox */
    &[type='number'] {
      -moz-appearance: textfield;
      appearance: textfield;
    }
  }
}

.suggestions-panel {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 1000;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-height: 300px;
  overflow-y: auto;
  margin-top: 4px;
}

.suggestions-header {
  padding: 8px 12px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.suggestion-item {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.2s;

  &:hover,
  &.active {
    background-color: #f5f7fa;
  }

  &:last-child {
    border-bottom: none;
  }
}

.suggestion-content {
  color: #606266;
  font-size: 12px;
  line-height: 1.4;
  margin-bottom: 6px;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
}

.suggestion-similarity {
  font-size: 11px;
  color: #909399;
  text-align: right;
}

/* 高亮样式 */
:deep(.highlight) {
  background-color: #fff3cd;
  color: #856404;
  padding: 1px 2px;
  border-radius: 2px;
  font-weight: 500;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .suggestions-panel {
    max-height: 200px;
  }

  .suggestion-item {
    padding: 8px;
  }

  .suggestion-content {
    -webkit-line-clamp: 2;
    line-clamp: 2;
  }
}
</style>
